<template>
  <!-- AdminMembershipInfo 入会信息 -->
  <PageContainer>
    <view class="container">
      <Header title="入会信息" />
      <view v-if="holdData" class="tip">资料已暂存,提交后生效</view>
      <ApplicationInfo :info="info" />
      <ApplyForm
        v-if="apiIsInit"
        :form-item-map="formItemMap"
        :answer-list="holdData || answerList"
        :btn-group-options="btnGroupOptions"
        form-interaction-mode="normal"
        @on-submit="onSubmit"
        @onChange="onChange"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  AdminMembershipInfo  入会信息 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { onLoad } from '@/router';
  import { reactive, ref, unref } from 'vue';
  import { type MemberApplyFormAudit } from '@/router/types/modules';
  import { adminMemberInfo, adminUpdateMemberInfo } from '@/api/admin';
  import { type AdminMemberInfoResult } from '@/api/admin/types';
  import ApplyForm from '../components/applyForm.vue';
  import { type FormItemVoMapItem } from '@/api/membership/formCompTypes';
  import { type customFormUserAnswerList } from '@/api/membership/types';
  import { isArray } from '@/utils/is';
  import { Toast } from '@/utils';
  import ApplicationInfo from './components/applicationInfo.vue';
  import { type OnchangeArgument } from '@/components/Form/types';
  import { type CardBottomBtnsOptions } from '@/components/TButtonGroup/types';
  import { getHoldData, setHoldData } from '@/utils/hold';
  import { removeHoldDataApi } from '@/api/hold';
  import { useUpload } from '@/hooks/core/useUpload';
  import { useEnv } from '@/hooks/core/useEnv';
  import { Api } from '@/api/admin';
  import { useAppStoreWithOut } from '@/store/modules/app';

  const id = ref<number>();
  let refresh: MemberApplyFormAudit['refresh'];
  const formItemMap = ref<FormItemVoMapItem>({});
  const answerList = ref<customFormUserAnswerList[]>([]);
  const apiIsInit = ref<boolean>(false);
  const info = ref<AdminMemberInfoResult>();

  const { globalConfig } = useAppStoreWithOut();
  const { getEnv } = useEnv();
  const { openDocument } = useUpload();

  const btnGroupOptions = reactive<CardBottomBtnsOptions>({
    submit: {
      text: '提交',
    },
    custom: {
      text: '下载入会表',
      clickFn: () => {
        openDocument({
          filePath: getEnv('BASE_URL') + Api.membershipFormPdf + `/${unref(id)}`,
          fileType: 'pdf',
          customFileName: `${globalConfig?.name}入会申请表`,
        });
      },
    },
    reset: {
      text: '暂存',
      clickFn: (vals) => {
        const data = getSubmitData(vals, true);
        setHoldData({
          businessType: 'adminMembershipInfo',
          businessId: `${unref(id)}`,
          content: data,
        }).then(() => Toast('暂存成功', 'none', 1500));
      },
    },
  });

  const companyId = ref<number>();

  const holdData = ref();
  async function __init() {
    if (id.value) {
      const r = await getHoldData<{ customMemberInfoAnswerList: customFormUserAnswerList[] }>({
        businessType: 'adminMembershipInfo',
        businessId: `${unref(id)}`,
      });
      if (r && r?.customMemberInfoAnswerList && r?.customMemberInfoAnswerList.length > 0) {
        holdData.value = r?.customMemberInfoAnswerList;
      }
      adminMemberInfo(id.value).then((r) => {
        info.value = r;
        companyId.value = r.companyId;
        formItemMap.value = r.customFormItemMap;
        answerList.value = r.customFormUserAnswerList;
        apiIsInit.value = true;
      });
    }
  }

  function onChange(op: OnchangeArgument) {
    const { val } = op;
    if (val) {
      companyId.value = val?.id;
    }
  }

  function getSubmitData(vals: { [x: string]: any }, IsContentStr: boolean = false) {
    const result = [];
    const d = info.value;
    for (const key in vals) {
      let content = vals[key] || '';
      if (!isArray(content)) content = content.toString().split(',');
      result.push({
        formItemId: Number(key),
        content: IsContentStr ? JSON.stringify(content) : content,
      });
    }
    return {
      companyId: companyId.value,
      memberId: id.value,
      leadingId: d?.leadingId,
      contactPersonId: d?.contactPersonId,
      customMemberInfoAnswerList: result,
    };
  }

  async function onSubmit(vals: { [x: string]: any }) {
    const data = getSubmitData(vals);
    await removeHoldDataApi({
      businessType: 'adminMembershipInfo',
      businessId: `${unref(id)}`,
    });
    await adminUpdateMemberInfo(data);
    Toast('资料修改成功', 'none', 1500);
    holdData.value = void 0;
    refresh?.();
  }

  onLoad<'AdminMembershipInfo'>((op) => {
    id.value = op.id;
    refresh = op.refresh;
    __init();
  });
</script>

<style lang="scss" scoped>
  .tip {
    color: #ff3434;
    font-size: 28rpx;
    text-align: center;
    height: 88rpx;
    line-height: 88rpx;
  }
</style>
